package org.ssq.mybatisPlusMonitor.Interceptor;


import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.ssq.mybatisPlusMonitor.entity.SlowSqlLog;
import org.ssq.mybatisPlusMonitor.services.SlowSqlLogService;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
})
public class SlowSqlLogInterceptor implements Interceptor {
    @Value("${mybatis-plus.monitor.max-time}")
    private Integer maxtime;

@Resource
private SlowSqlLogService slowSqlLogService;
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object returnValue = null;
        long start = System.currentTimeMillis();
        returnValue = invocation.proceed();
        try {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            Object parameter = null;
            if (invocation.getArgs().length > 1) {
                parameter = invocation.getArgs()[1];
            }
            String sqlId = mappedStatement.getId();
            /**
             * 在此处理表
             *
             * */
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            //获取配置信息
            Configuration configuration = mappedStatement.getConfiguration();
            String sql = geneSql(configuration, boundSql);
            log.info("==> mysql : " + sql);
            long end = System.currentTimeMillis();
            long time = (end - start);
            log.debug("<== sql执行历时：" + time + "毫秒");
            if (time >= maxtime) {
                log.warn("Slow SQL detected: Duration: {} ms, Query: {}", time, sql);
                if (!sqlId.contains("slowSqlLog")) {
                    SlowSqlLog log = new SlowSqlLog();
                    log.setMethodName(sqlId);
                    log.setExecuteSql(sql);
                    log.setRunTime(time);
                    log.setCreateTime(LocalDateTime.now());
                    slowSqlLogService.saveSqlLog(log);
                }
            }
        } catch (Exception e) {
            log.error("插件处理异常", e);
        }
        return returnValue;
    }


    private static String getParameterValue(Object obj) {
        String value;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(obj) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
        }
        return value;
    }


    public static String geneSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        return sql;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
    @Override
    public void setProperties(Properties properties) {
        String property = properties.getProperty("maxtime");
        if(null!=property&&!"".equals(property)) {
            this.maxtime = Integer.parseInt(property);
        }else {
            this.maxtime = 1000;
        }
    }

}
